package com.fzj.example.socket.tcp.nonblock.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * ClassName: NioTest
 * date: 2019/11/18 16:03
 * Description: TODO
 *
 * @author fanzj@bonree.com
 * @since JDK 1.8
 */
public class NioTest {

    public static void main(String[] args) throws IOException {

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8889));
        //
        int msgLen=1+2+3+4+5;
        ByteBuffer[] byteBuffers=new ByteBuffer[5];
        byteBuffers[0] = ByteBuffer.allocate(1);
        byteBuffers[1] = ByteBuffer.allocate(2);
        byteBuffers[2] = ByteBuffer.allocate(3);
        byteBuffers[3] = ByteBuffer.allocate(4);
        byteBuffers[4] = ByteBuffer.allocate(5);
        //
        SocketChannel socketChannel=serverSocketChannel.accept();
        while (true){
            int byteRead=0;
            //read-byteBuffers,对于byteBuffers是
            while(byteRead<msgLen){
                long len=socketChannel.read(byteBuffers);
                byteRead+=len;
                System.out.println("byteRead:"+byteRead);
                Arrays.asList(byteBuffers).stream().map(byteBuffer -> "positon:"+byteBuffer.position()+",limit:"+byteBuffer.limit()).forEach(System.out::println);
            }
            //复位，进行byteBuf写
            Arrays.asList(byteBuffers).stream().forEach(byteBuffer -> {
                byteBuffer.flip();
            });
            //写-byteBuffers通过通道向外输出，对于byteBuffers读
            int byteWrite=0;
            while (byteWrite<msgLen){
                long len=socketChannel.write(byteBuffers);
                byteWrite+=len;
                System.out.println("byteWrite"+byteWrite);
            }
            //buffer变成可写
            Arrays.asList(byteBuffers).forEach(byteBuffer -> {
                //可写
                byteBuffer.clear();
            });
            System.out.println("bytesRead:" + byteRead + ",bytesWritten:" + byteWrite + ",messageLength:"+msgLen);

        }
    }

}
